<template>
  <div>
    <el-dialog id="attachment" :visible.sync="show" width="950px" class="closeIcon" :title="$t(title)"
      :append-to-body="true" @close="close">
      <div class="top-flex">
        <div class="left">
          <el-button :class="num > 0 ? 'dele' : ''" :disabled="num > 0 ? false : true" size="small" @click="dele">
            {{ $t('删除附件') }}
          </el-button>
          <el-upload :headers="myHeaders" :action="$store.getters.updateURL + 'attachment/uploadAndSave'"
            :show-file-list="false" :on-success="handleSuccess" :on-progress="onProgress" :before-upload="beforeUpload"
            :data="uploadData">
            <el-button size="small" plain @click="getTypeCate">
              {{ $t('上传附件') }}
            </el-button>
          </el-upload>
          <el-button size="small" plain @click="showDialog = true">
            {{ $t('网络附件') }}
          </el-button>
        </div>
        <el-badge :value="num" :hidden="num > 0 ? false : true">
          <el-button :class="num > 0 ? 'orange' : ''" :type="num > 0 ? 'primary' : ''" :disabled="num > 0 ? false : true"
            size="small" @click="choose">
            {{ $t('使用选中附件') }}
          </el-button>
        </el-badge>
      </div>
      <el-dialog id="attachment" :visible.sync="showDialog" width="950px" class="closeIcon" :title="$t('添加网络附件')"
        :append-to-body="true">
        <el-form ref="urlForm" :model="urlForm" :rules="urlRules" label-width="60px">
          <el-form-item :label="`${$t('名称')}:`" prop="name">
            <el-input v-model="urlForm.name" />
          </el-form-item>
          <el-form-item :label="`${$t('附件地址')}:`" prop="url">
            <el-input v-model="urlForm.url" />
          </el-form-item>
          <el-form-item :label="`${$t('描述')}:`">
            <el-input v-model="urlForm.description" type="textarea" />
          </el-form-item>
          <div class="btn">
            <el-button @click="showDialog = false">{{ $t('取消') }}</el-button>
            <el-button type="primary" @click="uploadUrl">
              {{ $t('提交') }}
            </el-button>
          </div>
        </el-form>
      </el-dialog>
      <div class="content">
        <div class="left">
          <InputSearch @search="serarchCate" />
          <AttachmentCate ref="AttachmentCate" @update="getAttachmentList" />
        </div>
        <div class="right">
          <InputSearch @search="serarchAttachment" />
          <div v-loading="loading" class="attachment_box">
            <div v-for="item in attachmentData" :key="item.id" class="attachment_item">
              <!-- <div  id="item" @click="handelChoose(item)">

                <i class="el-icon-check" :class="currentClass(item.id)"></i>
              </div> -->

              <div id="video" :class="currentClass(item.id)" @click="handelChoose(item)">
                <el-image :src="item.url" alt="" v-if="item.type == 2" fit="cover" />
                <!-- 视频附件 -->
                <img src="~@/assets/icon-video.png" v-if="item.type == 3" alt="" class="icon" />
                <!-- 文档附件 -->
                <img src="~@/assets/icon-word.png" v-else-if="item.type == 4" alt="" class="icon" />
                <!-- 音频附件 -->
                <img src="~@/assets/icon-audio.png" v-else-if="item.type == 5" alt="" class="icon" />
                <!-- 压缩包附件 -->
                <img src="~@/assets/icon-rar.png" v-else-if="item.type == 1" alt="" class="icon" />
                <i class="el-icon-check" :class="currentClass(item.id)"></i>
              </div>
              <!-- <div
                v-else
                id="video"
                :class="currentClass(item.id)"
                @click="handelChoose(item)"
              >
                <i class="el-icon-tickets" />
              </div> -->
              <p class="attachment_name">{{ item.name }}</p>
            </div>
            <div class="attachment_item seat" />
            <div class="attachment_item seat" />
            <div class="attachment_item seat" />
            <div class="attachment_item seat" />
          </div>
          <el-pagination :current-page="page.currentPage" :page-sizes="page.pageSizes" :page-size="page.size"
            layout="total, prev, pager, next, jumper" :total="page.total"
            :hide-on-single-page="page.total < page.size ? true : false" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import attachmentApi from '@/api/system/attachment'
import compressImg from '@/utils/compressImg'

export default {
  props: {
    title: {
      type: String,
      default: '选择图片'
    },
    dialogShow: {
      type: Boolean,
      default: false
    },
    attachmentType: {
      default: 2
    }
  },
  data() {
    return {
      uploadData: {
        type: 2,
        attachment_cate_id: 0
      },
      showDialog: false,
      urlForm: {
        name: '',
        url: '',
        description: '',
        storage: 5
      },
      urlRules: {
        name: [
          {
            required: 'true',
            message: this.$t('请输入附件名'),
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: 'true',
            message: this.$t('请输入附件地址'),
            trigger: 'blur'
          }
        ]
      },
      cateTitle: '',
      cateList: [], // 附件分类列表
      show: false,
      fullscreen: false,
      loading: false,
      num: 0,
      attachmentData: [],
      imagelist: [],
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      headers: {},
      logoUrl: '',
      wechatUrl: '',
      imgUrl: this.$store.getters.updateURL,
      page: {
        total: 0,
        currentPage: 1,
        size: 18,
        pageSizes: [18]
      }, // 分页器
      currentNumber: [],
      currentItem: [],
      is_used: false,
      name: ''
    }
  },
  watch: {
    dialogShow(newQuestion, oldQuestion) {
      this.show = newQuestion
    },
    attachmentType(val, value) { }
  },
  created() {
    this.getAttachmentList()
  },
  mounted() {
    if (this.show) {
      this.getAttachmentList()
    }
  },
  methods: {
    // 添加网络附件
    uploadUrl() {
      const val = []
      val.push(this.urlForm)
      attachmentApi.attachmentSave(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.showDialog = false
          this.getAttachmentList(this.$refs.AttachmentCate.cate_id)
        } else {
          this.$message.error(res.smsg)
        }
      })
    },
    // 搜索附件分类
    serarchCate() {
      this.$refs.AttachmentCate.getCateList(this.cateTitle)
    },
    // 搜索附件
    serarchAttachment() {
      // console.log(this.$refs.AttachmentCate.cate_id)
      this.getAttachmentList(this.$refs.AttachmentCate.cate_id)
    },

    // 删除图片
    dele() {
      this.$confirm(this.$t('删除该文件'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          attachmentApi
            .attachmentDelete({ id: this.currentNumber })
            .then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.getAttachmentList()
              }
            })
        })
        .catch(() => { })
    },
    fullScreen() {
      this.fullscreen = !this.fullscreen
    },
    close() {
      this.$emit('update:dialogShow', this.show)
    },
    // 选中图片
    handelChoose(item) {
      console.log(item)
      // this.show = true
      const isIn = this.currentNumber.indexOf(item.id)
      if (isIn == -1) {
        this.currentNumber.push(item.id)
        this.currentItem.push(item)
      } else {
        this.currentNumber.splice(isIn, 1)
        this.currentItem.splice(isIn, 1)
      }
      this.num = this.currentNumber.length
    },
    currentClass(index) {
      const isIn = this.currentNumber.indexOf(index)
      if (isIn != -1) {
        return 'active'
      }
    },
    // 选择附件
    choose() {
      this.$emit('func', this.currentItem)
    },
    // 附件列表
    getAttachmentList(id) {
      this.is_used = false
      const val = {
        limit: this.page.size,
        page: this.page.currentPage,
        type: this.attachmentType,
        cate_id: id,
        name: this.name
      }
      this.currentNumber = []
      this.currentItem = []
      this.num = 0
      attachmentApi.attachmentList(val).then(res => {
        if (res.code == 0) {
          this.attachmentData = res.data
          this.$forceUpdate()
          this.page.total = res.count
          this.imagelist = []
          // 获取每张图片的地址
          for (var x = 0; x < this.attachmentData.length; x++) {
            this.imagelist.push(this.attachmentData[x].url)
          }
          // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
          for (var i = 0; i < this.attachmentData.length; i++) {
            var container = this.imagelist
            var frontArr = container.slice(0, i)
            var begindArr = container.slice(i, this.attachmentData.length)
            var list = begindArr.concat(frontArr)
            this.attachmentData[i].list = list
          }
        }
      })
    },
    // 点击上传
    getTypeCate() {
      this.uploadData.attachment_cate_id = this.$refs.AttachmentCate.cate_id
      // console.log(this.$refs.AttachmentCate.cate_id)
    },
    // 上传中
    onProgress() {
      this.loading = true
    },
    // 上传之前 压缩生成缩略图
    async beforeUpload(file) {
      const url = await compressImg(file, 0.2)
      this.uploadData.reduce_img = url.file
    },
    // 上传成功
    async handleSuccess(res, file, fileList) {
      this.loading = false
      if (res.code == 0) {
        this.getAttachmentList(this.$refs.AttachmentCate.cate_id)
      }
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getAttachmentList()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getAttachmentList()
    }
  }
}
</script>
<style lang="scss">
.content {
  .el-badge {
    margin-right: 10px;
  }

  .el-badge__content.is-fixed {
    right: 12px;
  }

  .el-badge__content {
    background-color: var(--huocms-com-color-primary);
    border-color: var(--huocms-com-color-primary);
  }
}

#attachment {
  .el-button.is-plain {
    border: solid 1px var(--huocms-com-color-primary);
    color: var(--huocms-com-color-primary);
  }

  .el-dialog__headerbtn i {
    font-weight: bold;
    color: var(--suq-cn-color-title);
  }

  // 浅橙色
  .orange.el-button--primary {
    background-color: #fe872b;
  }

  //黄色
  .yellow.el-button--primary {
    background-color: #f9b633;
  }

  //灰色 删除
  .el-button.dele {
    color: #333;
    background-color: #dddddd;
    border-color: #edeef3;
  }

  .el-dialog__header {
    background: #fff !important;
    border-radius: 10px 10px 0 0 !important;
    padding: 10px 20px 1px;
  }

  .el-dialog__body {
    padding: 15px 20px;
  }

  .el-dialog__title {
    color: var(--huocms-com-color-primary);
    font-size: 20px;
    font-weight: bold;
    line-height: 36px;
    // font-family: MicrosoftYaHei-Bold;
  }

  .el-dialog__title::before {
    display: inline-block;
    width: 4px;
    height: 20px;
    margin-right: 15px;
    border-radius: 4px;
    background-color: var(--huocms-com-color-primary);
    vertical-align: middle;
    content: '';
  }
}
</style>
<style scoped lang="scss">
.top-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    flex: 1;
    display: flex;

    .el-button {
      margin-right: 8px;
    }
  }
}

.btn {
  text-align: center;
}

.content {
  display: flex;
  border: solid 1px #eee;
  margin-top: 8px;

  .el-pagination {
    margin-top: 20px;
    margin-bottom: 0 !important;
  }

  .left {
    width: 225px;
    padding-top: 16px;

    .search-input {
      padding: 0 8px;
    }
  }

  .right {
    width: calc(100% - 220px);
    border-left: solid 1px #eee;
    padding: 16px;
    text-align: right;

    .search-input {
      width: 200px;
    }

    .attachment_box {
      margin-top: 20px;
      height: 400px;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-content: flex-start;

      .el-icon-check {
        font-size: 12px;
        text-align: center;
        line-height: 15px;
        color: #fff;
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background-color: var(--huocms-com-color-primary);
        position: absolute;
        bottom: 43px;
        right: 5px;
        display: none;
      }

      .el-icon-check.active {
        display: block;
      }

      .attachment_item.seat {
        height: 0;
      }

      .attachment_item {
        width: 16%;
        position: relative;

        .el-image {
          width: 100%;
          height: 100px;
          cursor: pointer;
          background-color: #eee;
          object-fit: cover;
        }

        #video {
          width: 100%;
          height: 100px;
          cursor: pointer;
          background-color: rgba(0, 0, 0, 0.2);
          text-align: center;

          .icon {
            width: 50px;
            margin-top: 25px;
          }
        }

        p {
          display: block;
          width: 100%;
          height: 35px;
          line-height: 35px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          text-align: center;
        }
      }
    }
  }
}
</style>
